package com.spring.dynamicdatasource.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 默认数据源配置
 *
 * @author HouKunLin
 * @date 2019/9/10 0010 15:15
 */
@Configuration
public class DefaultDataSourceConfig implements InitializingBean {
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Autowired
    @Qualifier("defaultDataSource")
    private DataSource dataSource;

    @Bean(name = "defaultDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource defaultDataSource(DataSourceProperties properties) {
        return DataSourceBuilder.create(properties.getClassLoader())
                .type(properties.getType())
                .url(properties.determineUrl())
                .username(properties.determineUsername())
                .password(properties.determinePassword())
                .driverClassName(properties.determineDriverClassName())
                .build();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        dynamicDataSource.setDefaultTargetDataSource(dataSource);
        dynamicDataSource.afterPropertiesSet();
    }
}
